

from zmq_socket import ZmqClientSub
import json
import pdb

class SequencerMessage(object):
	def __init__(self,group_id,tid,result):
		self.group_id = group_id
		self.tid = tid
		self.result = result


class SequencerConn(ZmqClientSub):
	"""Connect to sequencer by a zmq.SUB. And listen result for specified GroupID:TID."""
	def __init__(self,ip,port):
		super(SequencerConn,self).__init__(ip,port)
		self.setFilter("101")
		self.group_name_ = "group"
		self.tid_name_ = "tid"
		self.result_name_ = "to_pdca"

	def RecvOneMsgRaw(self):
		num = self.recv()
		date = self.recv()
		data_type = self.recv()
		sequencer_id = self.recv()
		data_json = self.recv()
		msg_obj = {"num":num, "date":date, "data_type":data_type, "sequencer_id":sequencer_id,"data_json":data_json}

		return msg_obj


	def RecvOneMsg(self):
		data_type = "0"

		while True:
			obj = self.RecvOneMsgRaw()
			if obj["data_type"] != data_type:
				# This is not the message we need, skip it.
				continue

			obj = json.loads(obj["data_json"])
			seq_result = obj["data"]
			if self.group_name_ in seq_result.keys() and self.tid_name_ in seq_result.keys() and self.result_name_ in seq_result.keys():
				break

		return seq_result

	def GetOneResultMsg(self):
		data = self.RecvOneMsg()
		return SequencerMessage(data[self.group_name_],data[self.tid_name_],data[self.result_name_])

